#include<unistd.h>
#include<iostream>
#include<vector>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;

vector<int> data;
const string grep = " ";

enum{
 OK = 0,
 OPEN_FILE_ERROR,
};

int SaveBegin()
{
   string name = to_string(time(nullptr));
   name += "back.up";
   //创建备份文件并写入
   FILE* fp = fopen(name.c_str(),"w");
   if(fp == NULL)
    return OPEN_FILE_ERROR;
  string datastr;
  //数据写入
  for(auto d : data)
  {
    datastr += to_string(d);
    datastr += grep;
  }
 fputs(datastr.c_str(),fp);
 fclose(fp);
 return OK;
}


//子进程帮我们备份
void Save()
{
  pid_t id = fork();
  if(id == 0)
  {
    int code = SaveBegin();
    exit(code);
  }
  int status = 0;
  pid_t rid = waitpid(id,&status,0);
  if(rid > 0)
  {
    int code = WEXITSTATUS(status);
    if(code  == 0)
      printf("备份成功 , exit code:%d\n",code);
    else
      printf("Save faile,exit code:%d\n",code);
  }
  else 
  {
    printf("error\n");
  }


}

int main()
{
  int cnt = 1;
  while(1)
  {
   data.push_back(cnt++);
   sleep(1);
  //每10一次备份
   if(cnt % 10 == 0)
   {
     Save();
   }
  }
 

  return 0;
}


